<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="referrer" content="no-referrer">
    <title>Ajax 文件上传示例</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .imgSizxe {
            width: 400px;
            height: 600px;
        }
        #result{
            width: 300px;
            height: 500px;
        }
    </style>
</head>
<body>
<h1>文件上传</h1>
<form id="uploadForm" enctype="multipart/form-data" method="post" action="uploadServlet">
    <input type="file" id="fileInput" name="file">
    <button type="button">上传</button>
</form>
<div id="result">
    <table>
        <tbody>
        </tbody>
    </table>
</div>
<script type="text/JavaScript" lanage="javascript">
    $(document).ready(function() {
        $('button').click(function() {
            var formData = new FormData($('#uploadForm')[0]);
            $.ajax({
                url: 'uploadServlet',
                type: 'post',
                data: formData,
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                success: function(response) {
                    console.log(response)
                    if(response == "false"){
                        alert('文件上传失败，请重新上传！');
                    } else {
                        var decodedImageUrl = decodeURIComponent(response); // 解码URL编码的字符串
                        var str = "<tr><td><img src='img/" + decodedImageUrl + "' alt='Uploaded Image' class='imgSizxe'></td></tr>";
                        $("#result tbody").append(str);
                    }
                },
                error: function(xhr, status, error) {
                    console.log(error);
                }
            });
        });
    });
</script>
</body>
</html>